package basic.study.leetcode;

import java.util.Stack;

/**
 * @ClassName Hard32
 * @Description 最长有效括号
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/19 9:34
 * @Version 1.0
 */
public class Hard32 {
    /**
     * 东涛规划
     */
    class Solution {
        public int longestValidParentheses(String s) {
            int maxans = 0;
            int[] dp = new int[s.length()];
            for (int i = 1; i < s.length(); i++) {
                if (s.charAt(i) == ')') {
                    if (s.charAt(i-1) == '(') {
                        dp[i] = (i >= 2?dp[i-2]:0) +2;
                    } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i-1]) == '('){
                        dp[i] = dp[i-1] + ((i - dp[i-1]) >= 2?dp[i - dp[i-1]]:0) + 2;
                    }
                }
                maxans = Math.max(maxans, dp[i]);
            }
            return maxans;
        }
    }

    /**
     * 栈解法
     */
    class Solution1 {
        public int longestValidParentheses(String s) {
            int maxans = 0;
            Stack<Integer> stack = new Stack<>();
            stack.push(-1);
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '(') {
                    stack.push(i);
                } else {
                    stack.pop();
                    if (stack.isEmpty()) {
                        stack.push(i);
                    } else {
                        maxans = Math.max(maxans, i - stack.peek());
                    }
                }
            }
            return maxans;
        }
    }
}
